import React, { useRef, useEffect, useState } from 'react';
import { Button, Space, Tooltip } from 'antd';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  VerticalAlignTopOutlined,
  VerticalAlignBottomOutlined
} from '@ant-design/icons';
import * as d3 from 'd3';

const FlowChartVisualization = ({ 
  nodes = [], 
  edges = [], 
  onNodeClick,
  onEdgeClick,
  editable = false,
  width = '100%',
  height = 500,
  direction = 'vertical' // vertical 或 horizontal
}) => {
  const svgRef = useRef(null);
  const containerRef = useRef(null);
  const [currentZoom, setCurrentZoom] = useState(1);
  const [flowDirection, setFlowDirection] = useState(direction);

  useEffect(() => {
    if (!nodes.length) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    const container = svg.append('g').attr('class', 'flowchart-container');
    
    // 创建缩放行为
    const zoomBehavior = d3.zoom()
      .scaleExtent([0.1, 4])
      .on('zoom', (event) => {
        container.attr('transform', event.transform);
        setCurrentZoom(event.transform.k);
      });

    svg.call(zoomBehavior);

    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;

    // 创建箭头标记
    const defs = container.append('defs');
    
    // 普通箭头
    defs.append('marker')
      .attr('id', 'arrowhead')
      .attr('viewBox', '0 -5 10 10')
      .attr('refX', 8)
      .attr('refY', 0)
      .attr('markerWidth', 6)
      .attr('markerHeight', 6)
      .attr('orient', 'auto')
      .append('path')
      .attr('d', 'M0,-5L10,0L0,5')
      .attr('fill', '#666');

    // 决策箭头（绿色）
    defs.append('marker')
      .attr('id', 'arrowhead-yes')
      .attr('viewBox', '0 -5 10 10')
      .attr('refX', 8)
      .attr('refY', 0)
      .attr('markerWidth', 6)
      .attr('markerHeight', 6)
      .attr('orient', 'auto')
      .append('path')
      .attr('d', 'M0,-5L10,0L0,5')
      .attr('fill', '#52c41a');

    // 决策箭头（红色）
    defs.append('marker')
      .attr('id', 'arrowhead-no')
      .attr('viewBox', '0 -5 10 10')
      .attr('refX', 8)
      .attr('refY', 0)
      .attr('markerWidth', 6)
      .attr('markerHeight', 6)
      .attr('orient', 'auto')
      .append('path')
      .attr('d', 'M0,-5L10,0L0,5')
      .attr('fill', '#ff4d4f');

    // 流程图布局算法
    const layoutFlowChart = () => {
      const layoutedNodes = [...nodes];
      
      // 拓扑排序找到层级
      const inDegree = new Map();
      const outEdges = new Map();
      
      // 初始化
      nodes.forEach(node => {
        inDegree.set(node.id, 0);
        outEdges.set(node.id, []);
      });
      
      // 计算入度和出边
      edges.forEach(edge => {
        inDegree.set(edge.target, (inDegree.get(edge.target) || 0) + 1);
        outEdges.get(edge.source).push(edge.target);
      });
      
      // 拓扑排序
      const levels = new Map();
      const queue = [];
      
      // 找到入度为0的节点作为起始点
      nodes.forEach(node => {
        if (inDegree.get(node.id) === 0) {
          queue.push({ id: node.id, level: 0 });
          levels.set(node.id, 0);
        }
      });
      
      // 如果没有入度为0的节点，选择第一个节点
      if (queue.length === 0 && nodes.length > 0) {
        queue.push({ id: nodes[0].id, level: 0 });
        levels.set(nodes[0].id, 0);
      }
      
      let maxLevel = 0;
      while (queue.length > 0) {
        const { id, level } = queue.shift();
        maxLevel = Math.max(maxLevel, level);
        
        outEdges.get(id).forEach(targetId => {
          if (!levels.has(targetId)) {
            levels.set(targetId, level + 1);
            queue.push({ id: targetId, level: level + 1 });
          }
        });
      }
      
      // 处理没有被访问到的节点
      nodes.forEach(node => {
        if (!levels.has(node.id)) {
          levels.set(node.id, maxLevel + 1);
        }
      });
      
      // 按层级分组
      const levelGroups = new Map();
      levels.forEach((level, nodeId) => {
        if (!levelGroups.has(level)) levelGroups.set(level, []);
        levelGroups.get(level).push(nodeId);
      });
      
      // 计算位置
      const padding = 80;
      const nodeSpacing = 120;
      
      if (flowDirection === 'vertical') {
        const levelHeight = (containerHeight - padding * 2) / Math.max(levelGroups.size - 1, 1);
        
        layoutedNodes.forEach(node => {
          const level = levels.get(node.id) || 0;
          const levelNodes = levelGroups.get(level);
          const index = levelNodes.indexOf(node.id);
          const levelWidth = (containerWidth - padding * 2) / Math.max(levelNodes.length - 1, 1);
          
          node.x = levelNodes.length === 1 ? containerWidth / 2 : padding + index * levelWidth;
          node.y = padding + level * levelHeight;
          node.fx = node.x;
          node.fy = node.y;
        });
      } else {
        const levelWidth = (containerWidth - padding * 2) / Math.max(levelGroups.size - 1, 1);
        
        layoutedNodes.forEach(node => {
          const level = levels.get(node.id) || 0;
          const levelNodes = levelGroups.get(level);
          const index = levelNodes.indexOf(node.id);
          const levelHeight = (containerHeight - padding * 2) / Math.max(levelNodes.length - 1, 1);
          
          node.x = padding + level * levelWidth;
          node.y = levelNodes.length === 1 ? containerHeight / 2 : padding + index * levelHeight;
          node.fx = node.x;
          node.fy = node.y;
        });
      }
      
      return layoutedNodes;
    };

    const layoutedNodes = layoutFlowChart();

    // 创建连接线
    const links = container.append('g')
      .attr('class', 'flowchart-links')
      .selectAll('g')
      .data(edges)
      .enter().append('g')
      .attr('class', 'link-group');

    links.each(function(d) {
      const group = d3.select(this);
      const source = layoutedNodes.find(n => n.id === d.source);
      const target = layoutedNodes.find(n => n.id === d.target);
      
      if (source && target) {
        // 根据边的类型选择不同的样式
        const edgeType = d.type || 'normal';
        let strokeColor = '#666';
        let markerEnd = 'url(#arrowhead)';
        
        if (edgeType === 'yes' || d.label === '是' || d.label === 'Yes') {
          strokeColor = '#52c41a';
          markerEnd = 'url(#arrowhead-yes)';
        } else if (edgeType === 'no' || d.label === '否' || d.label === 'No') {
          strokeColor = '#ff4d4f';
          markerEnd = 'url(#arrowhead-no)';
        }
        
        // 创建路径（直角连接）
        let pathData;
        if (flowDirection === 'vertical') {
          const midY = (source.y + target.y) / 2;
          pathData = `M${source.x},${source.y} L${source.x},${midY} L${target.x},${midY} L${target.x},${target.y}`;
        } else {
          const midX = (source.x + target.x) / 2;
          pathData = `M${source.x},${source.y} L${midX},${source.y} L${midX},${target.y} L${target.x},${target.y}`;
        }
        
        group.append('path')
          .attr('d', pathData)
          .attr('stroke', strokeColor)
          .attr('stroke-width', 2)
          .attr('fill', 'none')
          .attr('marker-end', markerEnd)
          .style('cursor', 'pointer')
          .on('click', (event) => {
            event.stopPropagation();
            onEdgeClick?.(d);
          });
        
        // 添加边标签
        if (d.label) {
          const labelX = flowDirection === 'vertical' ? 
            (source.x + target.x) / 2 : 
            (source.x + target.x) / 2;
          const labelY = flowDirection === 'vertical' ? 
            (source.y + target.y) / 2 : 
            (source.y + target.y) / 2;
          
          const labelGroup = group.append('g')
            .attr('transform', `translate(${labelX}, ${labelY})`);
          
          labelGroup.append('rect')
            .attr('x', -15)
            .attr('y', -8)
            .attr('width', 30)
            .attr('height', 16)
            .attr('rx', 8)
            .attr('fill', '#fff')
            .attr('stroke', strokeColor)
            .attr('stroke-width', 1);
          
          labelGroup.append('text')
            .text(d.label)
            .attr('text-anchor', 'middle')
            .attr('dy', '0.35em')
            .attr('font-size', 10)
            .attr('fill', strokeColor)
            .attr('font-weight', 'bold');
        }
      }
    });

    // 创建节点
    const nodeGroups = container.append('g')
      .attr('class', 'flowchart-nodes')
      .selectAll('g')
      .data(layoutedNodes)
      .enter().append('g')
      .attr('transform', d => `translate(${d.x},${d.y})`)
      .style('cursor', 'pointer')
      .on('click', (event, d) => {
        event.stopPropagation();
        onNodeClick?.(d);
      });

    // 根据节点类型绘制不同形状
    nodeGroups.each(function(d) {
      const group = d3.select(this);
      const nodeType = d.type || 'process';
      
      // 添加阴影滤镜
      if (!defs.select('#drop-shadow').node()) {
        const filter = defs.append('filter')
          .attr('id', 'drop-shadow')
          .attr('height', '130%');
        
        filter.append('feDropShadow')
          .attr('dx', 2)
          .attr('dy', 2)
          .attr('stdDeviation', 3)
          .attr('flood-opacity', 0.3);
      }
      
      switch (nodeType) {
        case 'start':
          // 开始 - 圆形
          group.append('circle')
            .attr('r', 25)
            .attr('fill', '#52c41a')
            .attr('stroke', '#fff')
            .attr('stroke-width', 3)
            .attr('filter', 'url(#drop-shadow)');
          break;
          
        case 'end':
          // 结束 - 双圆形
          group.append('circle')
            .attr('r', 25)
            .attr('fill', '#ff4d4f')
            .attr('stroke', '#fff')
            .attr('stroke-width', 3)
            .attr('filter', 'url(#drop-shadow)');
          
          group.append('circle')
            .attr('r', 20)
            .attr('fill', 'none')
            .attr('stroke', '#fff')
            .attr('stroke-width', 2);
          break;
          
        case 'decision':
          // 决策 - 菱形
          group.append('path')
            .attr('d', 'M-35,0 L0,-25 L35,0 L0,25 Z')
            .attr('fill', '#fa8c16')
            .attr('stroke', '#fff')
            .attr('stroke-width', 3)
            .attr('filter', 'url(#drop-shadow)');
          break;
          
        case 'subprocess':
          // 子流程 - 双边框矩形
          group.append('rect')
            .attr('x', -40)
            .attr('y', -20)
            .attr('width', 80)
            .attr('height', 40)
            .attr('rx', 5)
            .attr('fill', '#722ed1')
            .attr('stroke', '#fff')
            .attr('stroke-width', 3)
            .attr('filter', 'url(#drop-shadow)');
          
          group.append('rect')
            .attr('x', -35)
            .attr('y', -15)
            .attr('width', 70)
            .attr('height', 30)
            .attr('rx', 3)
            .attr('fill', 'none')
            .attr('stroke', '#fff')
            .attr('stroke-width', 1);
          break;
          
        case 'data':
          // 数据 - 平行四边形
          group.append('path')
            .attr('d', 'M-35,-20 L35,-20 L40,20 L-30,20 Z')
            .attr('fill', '#13c2c2')
            .attr('stroke', '#fff')
            .attr('stroke-width', 3)
            .attr('filter', 'url(#drop-shadow)');
          break;
          
        default:
          // 处理 - 矩形
          group.append('rect')
            .attr('x', -40)
            .attr('y', -20)
            .attr('width', 80)
            .attr('height', 40)
            .attr('rx', 5)
            .attr('fill', '#1677ff')
            .attr('stroke', '#fff')
            .attr('stroke-width', 3)
            .attr('filter', 'url(#drop-shadow)');
      }

      // 添加文本
      const text = group.append('text')
        .attr('text-anchor', 'middle')
        .attr('dy', '0.35em')
        .attr('fill', '#fff')
        .attr('font-size', 12)
        .attr('font-weight', 'bold')
        .style('pointer-events', 'none');

      // 处理长文本换行
      const words = d.label.split(' ');
      if (d.label.length > 8) {
        text.selectAll('tspan').remove();
        const lines = [];
        let currentLine = '';
        
        words.forEach(word => {
          if ((currentLine + word).length <= 8) {
            currentLine += (currentLine ? ' ' : '') + word;
          } else {
            if (currentLine) lines.push(currentLine);
            currentLine = word;
          }
        });
        if (currentLine) lines.push(currentLine);
        
        lines.forEach((line, i) => {
          text.append('tspan')
            .attr('x', 0)
            .attr('dy', i === 0 ? 0 : '1.2em')
            .text(line);
        });
      } else {
        text.text(d.label);
      }
    });

    // 添加入场动画
    nodeGroups
      .style('opacity', 0)
      .style('transform', d => `translate(${d.x},${d.y}) scale(0.5)`)
      .transition()
      .duration(500)
      .delay((d, i) => i * 100)
      .style('opacity', 1)
      .style('transform', d => `translate(${d.x},${d.y}) scale(1)`);

    links
      .style('opacity', 0)
      .transition()
      .duration(300)
      .delay(800)
      .style('opacity', 1);

  }, [nodes, edges, flowDirection]);

  // 控制函数
  const handleZoomIn = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom * 1.2)
    );
  };

  const handleZoomOut = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom / 1.2)
    );
  };

  const handleReset = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity
    );
    setCurrentZoom(1);
  };

  const toggleDirection = () => {
    setFlowDirection(prev => prev === 'vertical' ? 'horizontal' : 'vertical');
  };

  return (
    <div style={{ position: 'relative', width, height, border: '1px solid #d9d9d9', borderRadius: '8px', overflow: 'hidden', background: 'linear-gradient(135deg, #f0f9ff 0%, #f6ffed 100%)' }}>
      {/* 工具栏 */}
      <div style={{
        position: 'absolute',
        top: '8px',
        right: '8px',
        zIndex: 10,
        background: 'rgba(255, 255, 255, 0.95)',
        borderRadius: '6px',
        padding: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <Space size="small">
          <Tooltip title={flowDirection === 'vertical' ? '水平布局' : '垂直布局'}>
            <Button 
              size="small" 
              icon={flowDirection === 'vertical' ? <VerticalAlignTopOutlined /> : <VerticalAlignBottomOutlined />} 
              onClick={toggleDirection} 
            />
          </Tooltip>
          <Tooltip title="放大">
            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
          </Tooltip>
          <Tooltip title="缩小">
            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
          </Tooltip>
          <Tooltip title="重置">
            <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
          </Tooltip>
        </Space>
      </div>

      {/* SVG 画布 */}
      <div ref={containerRef} style={{ width: '100%', height: '100%' }}>
        <svg
          ref={svgRef}
          width="100%"
          height="100%"
          style={{ display: 'block' }}
        />
      </div>

      {/* 状态指示器 */}
      <div style={{
        position: 'absolute',
        bottom: '8px',
        left: '8px',
        background: 'rgba(0,0,0,0.7)',
        color: 'white',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '12px'
      }}>
        <Space size="small">
          <span>流程图</span>
          <span>|</span>
          <span>{flowDirection === 'vertical' ? '垂直' : '水平'}布局</span>
          <span>|</span>
          <span>缩放: {Math.round(currentZoom * 100)}%</span>
          <span>|</span>
          <span>节点: {nodes.length}</span>
        </Space>
      </div>
    </div>
  );
};

export default FlowChartVisualization;